# 自定义用户认证后端类

from django.contrib.auth.backends import ModelBackend
import re
from .models import User
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData

from django.conf import settings

def get_user_by_account(account):
    """
       根据account账号查询用户
       :param account: 用户名或者手机号
       :return: user
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)

    except User.DoesNotExist:
        return None
    # else:
    return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定义用户认证后端"""

    def authenticate(self,request, username=None, password=None, **kwargs):
        """
        重写认证方法实现多张号登陆
        :param request:
        :param username:
        :param password:
        :param kwargs:
        :return: user
        """
        # 调用上面的方法,根据传入的username获取user对象。username可以是手机号也可以是账号
        user = get_user_by_account(username)
        # 校验user是否存在并校验密码是否正确
        if user and user.check_password(password):
            return user


def generate_verify_email_url(user):
    # 创建加密对象
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600*24)
    # 需加密的数据
    data = {'user_id': user.id, 'email': user.email}
    # 加密,加密后的数据是二进制,需要decode
    token = serializer.dumps(data).decode()

    email_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return email_url


def check_token_to_user(token):
    serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600*24)
    try:
        data = serializer.loads(token)
    except BadData:
        return None
    else:
        user_id = data.get('user_id')
        email = data.get('email')
        try:
            user = User.objects.get(id=user_id, email=email)
        except User.DoesNotExist:
            return None
        else:
            return user



